package com.rad.net.protocol.android.utils;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

/**
 * 类说明：联网模块的工具类
 * 
 * @author kalui.huang
 * @date 2014年8月19日
 * @version 1.0
 */
public class NetUtils {
	private NetUtils(){}
	/**
	 * 判断当前网络连接是否为cmwap
	 * 
	 * @param context android上下文
	 * @return true 是cmwap连接
	 *               false 不是cmwap连接
	 */
	public static boolean isCmwap(Context context) {
		ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo netWrokInfo = manager.getActiveNetworkInfo();
		if (netWrokInfo == null) {
			return false;
		}
		String typeName = netWrokInfo.getTypeName();
		String extraInfo = netWrokInfo.getExtraInfo();

        return "MOBILE".equalsIgnoreCase(typeName)
                && ("cmwap".equalsIgnoreCase(extraInfo) || "3gwap".equalsIgnoreCase(extraInfo)
                || "uniwap".equalsIgnoreCase(extraInfo) || "ctwap".equalsIgnoreCase(extraInfo));
	}

	/**
	 * 得到一个cmwap连接
	 * 
	 * @param requestUrl 请求的url
	 * @return  httpUrlConnection对象
	 * @throws IOException 
	 */
	public static HttpURLConnection getCmwapConnect(String requestUrl) throws IOException {
		URL url = new URL(requestUrl);
		HttpURLConnection con;
		String host = url.getHost();
		int port = url.getPort();
		if (port == -1) {
			requestUrl = requestUrl.replaceAll(host, "10.0.0.172:80");
		} else {
			requestUrl = requestUrl.replaceAll(host + ":" + port, "10.0.0.172:80");
		}
		url = new URL(requestUrl);
		con = (HttpURLConnection) url.openConnection();
		String xOnlineHost = null;
		if (port == -1) {
			xOnlineHost = host;
		} else {
			xOnlineHost = host + ":" + port;
		}
		con.setRequestProperty("Host", "10.0.0.172");
		con.setRequestProperty("X-Online-Host", xOnlineHost);
		return con;
	}

}
